<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class MY_Controller extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        session_start();
    }

    function alert_message($type, $msg = '', $url = '')
    {
//        header("Content-type:text/html;charset=utf-8");
        if ($type == 1) {
            if ($url) {
                echo "<script type='text/javascript'>alert('" . $msg . "');window.location.href='" . $url . "'</script>";
            } else {
                echo "<script type='text/javascript'>alert('" . $msg . "')</script>";
            }
        } else {
            echo "<script type='text/javascript'>alert('" . $msg . "');window.location.href='" . $url . "'</script>";
        }
    }

    function checkLogin()
    {
        if (!$_SESSION['adminId']) {
            $this->alert_message(0, '请先登录', site_url('login/index'));
        }
    }
    public function output($result,$fileName)
    {
        $i=1;
        //加载PHPExcel的类
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/IOFactory');
//创建PHPExcel实例
        $excel = new PHPExcel();

        foreach ($result as $value) {
            $start = (ord("A"));
            foreach ($value as $v) {
//为单元格赋值
                $excel->getActiveSheet()->setCellValue(chr($start) . $i, $v);
////合并单元格
//        $excel->getActiveSheet()->mergeCells('A1:A2');
//设置单元格内文字垂直居中
                $excel->getActiveSheet()->getStyle(chr($start) . $i)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
//设置单元格内文字自动换行
                $excel->getActiveSheet()->getStyle(chr($start) . $i)->getAlignment()->setWrapText(true);
//为单元格添加注释
                $excel->getActiveSheet()->getComment(chr($start) . $i)->getText()->createTextRun('hello');
//设置单元格文字颜色
                //   $excel->getActiveSheet()->getStyle('A1')->getFont()->getColor->setARGB(PHPExcel_Style_Color::COLOR_RED);
                $start++;
            }
            $i++;
        }
//输出到浏览器
        $write = new PHPExcel_Writer_Excel5($excel);
        ob_end_clean();//清除缓冲区,避免乱码
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl;charset=UTF-8");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename='.$fileName.'.xlsx');
        header("Content-Transfer-Encoding:binary");
        $write->save('php://output');
    }
}
